#!/usr/bin/python
# coding=utf-8

''' 
get user info and save these to db
'''

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
import time, datetime
import config
import userplatform

url = config.url
#url = ".."
timezone = config.timezone

class Record(db.Model):
    string_ref = db.StringProperty(required = True)
    string_ip = db.StringProperty(required = True)
    string_os = db.StringProperty(required = False)
    string_browser = db.StringProperty(required = False)
    date = db.DateTimeProperty(auto_now_add = True)

class lookrecord(webapp.RequestHandler):
    def get(self):
        adjustTimeZone = datetime.timedelta(hours=timezone)
        data = db.GqlQuery('SELECT * FROM Record ORDER BY date desc')
        for value in data:
            self.response.out.write(value.string_ref)
            self.response.out.write(value.string_ip)
            self.response.out.write(value.string_os)
            self.response.out.write(value.string_browser)
            self.response.out.write(value.date + adjustTimeZone)
            self.response.out.write('</br>')
            
class getref(webapp.RequestHandler):
    def get(self, slug):
        self.response.out.write(('''document.write("<script language='JavaScript' \
        src='%s/insert?ref="+escape(document.referrer)+"&user=%s'></script>")'''%(url, slug)))

class insert(webapp.RequestHandler):
    def get(self):
        self.response.out.write("document.write( 'from %s')"%self.request.get("ref"))
        ref = self.request.get("ref")
        if ref == "":
            ref = "direct"
        ip = self.request.remote_addr;
        osys = userplatform.get_system(self.request.headers["User-Agent"])
        bw = userplatform.get_browser(self.request.headers["User-Agent"])
        db = Record( string_ref = ref , string_ip = ip, string_os = osys, string_browser = bw)
        db.put()
        #self.response.out.write(bw)

application = webapp.WSGIApplication([
  ('/record', lookrecord),
  ('/record/(.*)', getref),
  ('/insert', insert)
], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
